/*
* 并发请求
* @param
* */


function concurRequest(urls, maxNum) {
    return new Promise((resolve) => {
        if (urls.length === 0) {
            resolve([])
            return;
        }
        const results = []
        let index = 0
        let resCount = 0

        async function request() {
            const i = index
            const url = urls[index]
            index++
            try {
                //   .then(response => response.json())
                //                    .then(json => console.log(json))
                const res = await fetch(url)
                // 正确结果加入到结果列表
                results[i] = res
            } catch (err) {
                // error结果加入到结果列表
                results[i] = err
            } finally {
                // 所有请求都完了
                resCount++
                if (resCount === urls.length) {
                    console.log('over')
                    resolve(results)
                }
                request()
            }
            console.log('result=', results)
        }

        const times = Math.min(maxNum, urls.length)
        for (let i = 0; i < times; i++) {
            request()
        }
    })
}

const urls = []

for (let i = 0; i < 100; i++) {
    urls.push('https://jsonplaceholder.typicode.com/todos/' + i)
}
concurRequest(urls, 20)